package cs342.project1.mathNotebook.xml;

import java.io.*;
import java.util.Collection;

import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import cs342.project1.mathNotebook.notebook.NotebookEntry;

/**
 * Writes Notebook entries to an XML file
 * @author Jared Schlicht
 * @author Gabrielle DuBois
 *
 */
public class XMLWriter extends NotebookWriter {

	/**
     * @see cs342.project1.mathNotebook.xml.NotebookWriter#NotebookWriter(java.io.ByteArrayOutputStream)
     */
	public XMLWriter (ByteArrayOutputStream outStream){
		super(outStream);
	}//constructor

    /**
     * @see cs342.project1.mathNotebook.xml.NotebookWriter#saveStream(java.util.Collection)
     */
    public ByteArrayOutputStream saveStream(final Collection<NotebookEntry> entries) {

		XMLOutputFactory factory = XMLOutputFactory.newInstance();
		try {
			XMLStreamWriter writer = factory.createXMLStreamWriter(out);
			writer.writeStartDocument();
			writer.writeStartElement("notebook");
			for (NotebookEntry entry : entries) {
				writer.writeStartElement("formula");
				writer.writeAttribute("equation", entry.functionString);
				for (Double tangentPoint : entry.tangentPoints) {
					writer.writeStartElement("tangent");
					writer.writeAttribute("point", tangentPoint.toString());
					writer.writeEndElement();
				}
				writer.writeEndElement();
			}
			writer.writeEndElement();
			writer.writeEndDocument();
			writer.flush();
		} catch (XMLStreamException e) {
			System.out.println("XMLWriter.saveStream() error: " + e);
		}

		return out;
    }//saveStream()

}//XMLWriter
